import { MessageBox } from 'element-ui'
import { message } from '@common/assets/js/resetMessage'
import common from '@common/api/common'
import utils from '@common/utils/utils'

const checkSelection = (list, multi = false) => {
    if (!utils.isNotEmptyList(list)) {
        if (multi) {
            message.error('请先勾选一条或者多条记录')
        } else {
            message.error('请先勾选一条记录')
        }
        return false
    }
    if (!multi && list.length > 1) {
        message.error('只能勾选一条记录')
        return false
    }
    return true
}
const fetchData = ({ url, data = {}, error = true, addLog = true }) => {
    const fun = () => {
    }
    return common.requestData(url, data, fun, fun, fun, addLog).then(result => {
        if (result.code !== 0) {
            return Promise.reject(result)
        }
        return result
    }).catch(err => {
        if (error) {
            message.error(err.message)
        }
        return Promise.reject(err)
    })
}

export const deleteConfirmBySids = opt => {
    return new Promise((resolve, reject) => {
        let list = []
        if (!opt.row) {
            if (!checkSelection(opt.list, opt.multi)) {
                reject()
                return
            }
            list = opt.list.map(item => $.extend({}, item));
        } else {
            list.push(opt.row)
        }
        if (typeof opt.check === 'function') {
            if (!opt.check(list)) {
                return;
            }
        }
        const sids = list.map(item => item.sid)
        if (!opt.message) {
            opt.message = '是否继续删除？'
        }
        MessageBox.confirm(opt.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() => {
            if (!opt.url) {
                resolve()
                return
            }
            fetchData({
                url: opt.url,
                data: {
                    sids,
                },
            }).then(() => {
                message.success('删除成功')
                resolve()
            }).catch(() => {
                reject()
            })
        }).catch(() => {
            reject()
        })
    })
}
